package dxn.nl.export.deal.consumer;

import dxn.nl.file.biz.po.AppModelPo;
import dxn.nl.file.biz.po.FileExportApplyDetail;
import dxn.nl.file.biz.po.FileImportFileDetail;
import dxn.nl.file.biz.service.ConsumerBaseService;
import dxn.nl.file.biz.service.ExportFileBaseService;
import dxn.nl.file.biz.service.ImportFileBaseService;
import dxn.nl.file.client.model.enums.ExportFileTypeEnum;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class ThreadManager {
    public final static ConcurrentHashMap<String,ThreadPoolExecutor> topicThreadPoolMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<Long, String> exportCache = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<Long, String> uploadCache = new ConcurrentHashMap<>();
    private static List<String> exportList = new ArrayList<>();
    private static List<String> importList = new ArrayList<>();

    public static ConsumerBaseService consumerBaseService;

    public static ExportFileBaseService exportFileBaseService;
    public static ImportFileBaseService importFileBaseService;

    public static void initThreadPool(List<AppModelPo> list) {
        for(AppModelPo topicDto : list)
        {
            if(topicDto.getTypeCode() == ExportFileTypeEnum.export.code)
            {
                exportList.add(topicDto.getTag());
            }
            else {
                importList.add(topicDto.getTag());
            }

            String key = topicDto.getTag()+topicDto.getTypeCode();
            if(!topicThreadPoolMap.containsKey(topicDto.getTag()))
            {
                ThreadPoolExecutor treeExecutorPool = new ThreadPoolExecutor(1, 10
                        ,15, TimeUnit.MINUTES,
                        new LinkedBlockingDeque<Runnable>(6),
                        new RejectedExecutionHandler() {
                            @Override
                            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                                System.out.println("拒绝了");
                            }
                        });
                topicThreadPoolMap.put(key,treeExecutorPool);
            }
        }
    }

    public static void selectAndPush()
    {
        loadExport();
        loadImport();
        refreshIdLock();
        removeDeadLock();
    }

    private static void loadExport()
    {
        for(String tag : exportList)
        {
            try {
                String key = tag+"10";
                // 查找线程池
                ThreadPoolExecutor taskExecutor = topicThreadPoolMap.get(key);
                if(taskExecutor == null)
                {
                    return ;
                }
                if(taskExecutor.getQueue().size()>5)
                {
                    return ;
                }
                //taskExecutor.getQueue().size()
                List<FileExportApplyDetail> idList = exportFileBaseService.selectNeedDealRow(tag);
                if (!CollectionUtils.isEmpty(idList)) {
                    for (FileExportApplyDetail applyDetail : idList) {
                        taskExecutor.execute(new ExportDealConsumer(applyDetail.getId(),ExportFileTypeEnum.export.code));
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }

    private static void loadImport()
    {
        for(String tag : exportList)
        {
            try {
                String key = tag+"20";
                // 查找线程池
                ThreadPoolExecutor taskExecutor = topicThreadPoolMap.get(key);
                if(taskExecutor == null)
                {
                    return ;
                }
                if(taskExecutor.getQueue().size()>10)
                {
                    return ;
                }
                //查询数据 16条
                List<FileImportFileDetail> idList = importFileBaseService.selectNeedDealRow(tag);
                if (!CollectionUtils.isEmpty(idList)) {
                    for (FileImportFileDetail applyDetail : idList) {
                        // 执行
                        taskExecutor.execute(new ExportDealConsumer(applyDetail.getId(),ExportFileTypeEnum.upload.code));
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }

    private static void refreshIdLock()
    {
        // 使用Iterator遍历HashMap并删除特定条目
        Iterator<Map.Entry<Long, String>> iterator = exportCache.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, String> entry = iterator.next();
            // 刷新时间
            consumerBaseService.refreshLockId(entry.getKey(),ExportFileTypeEnum.export.code,entry.getValue());
        }

        // 使用Iterator遍历HashMap并删除特定条目
        Iterator<Map.Entry<Long, String>> iterator2 = uploadCache.entrySet().iterator();
        while (iterator2.hasNext()) {
            Map.Entry<Long, String> entry = iterator2.next();
            // 刷新时间
            consumerBaseService.refreshLockId(entry.getKey(),ExportFileTypeEnum.upload.code,entry.getValue());
        }
    }

    private static void removeDeadLock()
    {
        consumerBaseService.removeDeadlockId();
    }
}
